package com.bosssoft.cloud.wechat.infrastructure.config;

import com.bosssoft.cloud.wechat.infrastructure.interceptor.VerifyCodeInterceptor;
import com.bosssoft.cloud.wechat.infrastructure.processor.RequestParamsMethodProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.*;

import java.util.List;

/**
 * 不要用WebMvcConfigurerAdapter（废弃）或WebMvcCOnfigurer，尽量直接新建对应配置类
 *
 * @author wcy create on 2021/7/23 18:05 下午
 */
@Configuration
public class WebConfig {

    @Autowired
    private VerifyCodeInterceptor verifyCodeInterceptor;

    @Bean
    public WebMvcConfigurer globalWebConfig() {
        return new WebMvcConfigurerAdapter() {

            /**
             * 异步
             */
            @Override
            public void configureAsyncSupport(AsyncSupportConfigurer asyncSupportConfigurer) {
                asyncSupportConfigurer.setDefaultTimeout(30000);
            }

            /**
             * 内容协商
             */
            @Override
            public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
                configurer.defaultContentType(MediaType.APPLICATION_JSON_UTF8);
            }

            /**
             * 跨域
             */
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedOrigins("*")
                        .allowedMethods("GET", "POST", "PUT", "DELETE")
                        .allowedHeaders("Origin", "X-Requested-With", "Content-Type", "Accept")
                        .allowCredentials(true) // cookie跨域
                        .maxAge(3600);
            }

            /**
             * 拦截器
             */
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                registry.addInterceptor(verifyCodeInterceptor).addPathPatterns("/**");
            }

            /**
             * 参数处理器
             */
            @Override
            public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
                argumentResolvers.add(new RequestParamsMethodProcessor());
            }
        };
    }
}